package sf.core.service.impl;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Created by ligen on 16-3-3.
 */

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import sf.core.exception.SugarException;
import sf.core.service.SmsService;

@Service
public class SmsServiceImpl implements SmsService {

	private Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

	private static DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

	private OkHttpClient client;

	private String appId;

	private String accountSid;

	private String accountToken;

	private Gson gson;

	public SmsServiceImpl() {

		client = new OkHttpClient();
		this.accountSid = "8a48b5514d32a2a8014d418393dc0a64";
		this.accountToken = "82fbef7af903494393a6ef937d9528f4";
		this.appId = "aaf98f894d328b13014d4184b8ba0a72";
		gson = new Gson();
	}

	public void sendVerificationCode(String mobile, String code) throws SugarException {

		String json = toJson(mobile, "19299", code, "30");
		send(json);

	}

	public void sendNotificationText(String to, String mobile, String action, String time, String title)
			throws SugarException {

		String json = toJson(to, "46090", mobile, action, time, title);
		send(json);

	}

	private void send(String json) throws SugarException {

		String now = format.format(new Date());
		String signature = DigestUtils.md5Hex(this.accountSid + this.accountToken + now).toUpperCase();
		String auth = Base64.getEncoder().encodeToString((this.accountSid + ":" + now).getBytes());
		String url = String.format("https://app.cloopen.com:8883/2013-12-26/Accounts/%s/SMS/TemplateSMS?sig=%s",
				this.accountSid, signature);

		RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

		Request request = new Request.Builder().url(url).post(body).header("Authorization", auth)
				.header("Accept", "application/json").build();

		Response response;
		try {
			response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				String result = response.body().string();
				YunResult yun = gson.fromJson(result, YunResult.class);
				if (!"000000".equals(yun.statusCode)) {
					logger.error("Send message failed, status code is " + yun.statusCode);
					throw new SugarException(8005, "send message failed");
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			throw new SugarException(8005, "send message failed");
		}

	}

	public class YunResult {

		public String statusCode;

		public Template TemplateSMS;

		public class Template {

			public String dateCreated;
			public String smsMessageSid;
		}
	}

	private String toJson(String mobile, String templateId, String... params) {

		JsonObject root = new JsonObject();
		root.addProperty("to", mobile);
		root.addProperty("appId", this.appId);
		root.addProperty("templateId", templateId);
		JsonArray datas = new JsonArray();
		for (String param : params) {
			datas.add(new JsonPrimitive(param));
		}
		root.add("datas", datas);
		return root.toString();
	}

}
